<?php
class UserRegnValidator {
	private $_passed = false,
			$_inviteCode = "098765",
			$_errors = array(),
			$_db = null;

	public function __construct() {
		$dbHost = $GLOBALS["a.dbHost"];
		$dbMain = $GLOBALS["a.dbMain"];
		$dbUser = $GLOBALS["a.dbUser"];
		$dbPass = $GLOBALS["a.dbPass"];
		$this->_db = new DBG($dbMain, $dbUser, $dbPass, $dbHost);
	}

	public function check($source, $items = array()) {
		
		foreach($items as $item => $rules) {
			foreach($rules as $rule => $rule_value) {
				
				$value = trim($source[$item]);

				if($rule === 'required' && $rule_value === true && empty($value)) {
					$this->addError("<b>{$item}</b> is required.");
				} else if (!empty($value)) {

					switch($rule) {
						case 'min':
							if(strlen($value) < $rule_value) {
								$this->addError("<b>{$item}</b> must be a minimum of <b>{$rule_value}</b> characters.");
							}
						break;
						case 'max':
							if(strlen($value) > $rule_value) {
								$this->addError("<b>{$item}</b> must be a maximum of <b>{$rule_value}</b> characters.");
							}
						break;
						case 'matches':
							if($value != $source[$rule_value]) {
								$this->addError("<b>{$rule_value}</b> must match <b>{$item}</b>.");
							}
						break;
						case 'default':
							if($value != $this->_inviteCode) {
								$this->addError("<b>Invite Code</b> not found!");
							}
						break;
						case 'email':
							$check = $this->_db->select('users', array("loginID" => "$value"));
							if (preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$value)) {
								if($check->count()) {
									$this->addError("<b>{$item}</b> is already taken.");
								}
															
							} else {
								$this->addError("<b>{$item}</b> is not a Valid e-mail Address.");
							}

						break;
					}

				}

			}
		}

		if(empty($this->_errors)) {
			$this->_passed = true;
		}

		return $this;
	}

	protected function addError($error) {
		$this->_errors[] = $error;
	}

	public function passed() {
		return $this->_passed;
	}

	public function errors() {
		return $this->_errors;
	}
}